import mqtt from 'mqtt'
import Notification from '/@/utils/notification'
import {Session} from '/@/utils/storage';
export default {
  mqttClient: null,
  isConnected: false,
  subscribeSuccess: false,
  receiveNews: '',
  options: {
    host: 'mqtt.wocoding.cn',
    port: 8084,
    clean: true, // 保留会话
    connectTimeout: 4000, // 超时时间
    reconnectPeriod: 4000, // 重连时间间隔
    // 认证信息
    username: 'wocoding',
    password: 'jc611'
  },
  subscription: {
    topic: 'jadmin_wocoding/+/+',
    qos: 1
  },
  publish: {
    topic: 'jadmin_wocoding',
    qos: 1
  },
  instance: null,
  init () {
    let _this = this
    try {
      _this.instance = mqtt.connect('wss://mqtt.wocoding.cn:8084/mqtt', _this.options)
    } catch (error) {
      console.log('mqtt.connect error', error)
    }
    _this.instance.on('connect', () => {
      _this.isConnected = true
      // _this.instance.publish();
      // 订阅
      const {topic, qos} = _this.subscription
      _this.instance.subscribe(topic, {qos}, (error, res) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        _this.subscribeSuccess = true
        // console.log('Subscribe to topics res', res)
      })
    })
    _this.instance.on('error', error => {
      _this.isConnected = false
      console.log('Mqtt-ERR', error)
    })
    _this.instance.on('disconnect', () => {
      _this.reconnect()
    })
    _this.instance.on('offline', () => {
      _this.reconnect()
    })
    _this.instance.on('message', (topic, message) => {
      _this.receiveNews = _this.receiveNews.concat(message)
      console.log(`Received message ${message} from topic ${topic}`)
      if (!Session.get('token')) {
        _this.instance.end()
        _this.instance = null
      } else {
        Notification.handleNotification('<a href="http://www.baid.com">测试数据</a>', 'http://cdn.wocoding.cn/markdoc/20231016/5cff1cb978ec90218f6c0ba0258c0ae7.png')
      }
    })
  },
  reconnect () {
    let _this = this
    let interval = setInterval(() => {
      if (!_this.isConnected) {
        this.init()
      }
      clearInterval(interval)
    }, 3000)
  }
}
